package com.tianji.promotion.utils;

import com.tianji.common.utils.BooleanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class RedisLock {
    private final String key;
    private final StringRedisTemplate redisTemplate;

    //获取锁
    public boolean tryLock(String lockId, Long leassTime, TimeUnit unit) {
        //设置锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, lockId, leassTime, unit);

        return BooleanUtils.isTrue(success);
    }

    //释放锁
    public void unLock(String lockId) {
        //1.拿到redis中的锁id(当前线程的锁id)
        String redisLockId = redisTemplate.opsForValue().get(key);
        //传进来的锁idlockId   与 redis中的锁id不相同不能删（防止第二种误删锁）
        if (Objects.equals(redisLockId, lockId)) {
            redisTemplate.delete(key);
        }
    }
}
